package manager

import (
	"fmt"
	"github.com/cihub/seelog"
	"kyland.com/eagle/lib/eagle"
	"kyland.com/eagle/lib/http"
	"kyland.com/eagle/lib/ipfs"
	"kyland.com/eagle/lib/localhost"
)

type Share struct {
	Cid  string `json:"cid"`
	Path string `json:"path"`
}

func AddShareFile(name string) (string, error) {
	client := ipfs.NewIpfsClient()
	return client.Add(name)
}

func GetShareFile(share *Share) error {
	seelog.Infof("cid, output: %s, %s", share.Cid, share.Path)
	client := ipfs.NewIpfsClient()
	err := client.Get(share.Cid, share.Path)
	if err != nil {
		return err
	}

	return nil
}

func SendToPeers(path, cid string) {
	for _, mem := range GetNodes() {
		if mem.Addr == localhost.HostIp() || mem.Status != "alive" {
			continue
		}

		ret := struct {
			Status struct {
				Code string `json:"code"`
				Msg  string `json:"msg"`
			} `json:"status"`
		}{}
		addr := fmt.Sprintf("http://%s:%s/v1/file/sendToPeers", mem.Addr, eagle.GetPort())
		param := map[string]string{
			"cid":  cid,
			"path": path,
		}
		err := http.JsonPostStruct(addr, ret, param)
		if err != nil {
			seelog.Errorf("send to peers %s failed: %v", addr, err)
		}
	}
}
